package org.example.ws;

import com.alibaba.fastjson.JSON;
import org.example.config.GetHttpSessionConfig;
import org.example.pojo.User;
import org.example.utils.MessageUtils;
import org.example.ws.pojo.Message;
import org.springframework.stereotype.Component;

import javax.annotation.processing.Messager;
import javax.servlet.http.HttpSession;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@Component
@ServerEndpoint(value = "/chat", configurator = GetHttpSessionConfig.class)
public class ChatEndPoint {

    private static final Map<String, Session> onlineUsers = new ConcurrentHashMap<>();
    private HttpSession httpSession;

    /**
     * 建立WebSocket连接
     *
     * @param session
     */
    @OnOpen
    public void onOpen(Session session, EndpointConfig config) {
        // 1.将session进行保持
        this.httpSession = (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
        String user = (String) this.httpSession.getAttribute("user");
        onlineUsers.put(user, session);
        // 2.广播消息，需要将登陆的所有用户推送给所有的用户
        String message = MessageUtils.getMessage(true, null, getFriends());
        broadcastAllUsers(message);
    }

    public Set getFriends() {
        return onlineUsers.keySet();
    }


    /**
     * 广播所有用户
     *
     * @param message
     */
    private void broadcastAllUsers(String message) {
        onlineUsers.forEach((username, session) -> {
            try {
                // 发送消息
                session.getBasicRemote().sendText(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    /**
     * 关闭WebSocket连接
     *
     * @param session
     */
    @OnClose
    public void onClose(Session session) {
        //1.从onlineUsers中删除
        String user = (String) this.httpSession.getAttribute("user");
        onlineUsers.remove(user);
        //2.通知所有用户，当前用户下线了
        String message = MessageUtils.getMessage(true, user, getFriends());
        broadcastAllUsers(message);
    }

    /**
     * 接收消息
     *
     * @param message
     */
    @OnMessage
    public void onMessage(String message) {
        try {
            //将消息推送给指定的用户
            Message msg = JSON.parseObject(message, Message.class);
            //获取消息接收方的用户名
            String toName = msg.getToName();
            String mess = msg.getMessage();
            Session session = onlineUsers.get(toName);
            String user = (String) this.httpSession.getAttribute("user");
            String msg1 = MessageUtils.getMessage(false, user, mess);
            session.getBasicRemote().sendText(msg1);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
